package com.ygqh.baby.handler;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.PromotionType;
import com.ygqh.baby.ao.SalesPlatform;
import com.ygqh.baby.model.YgShoppingCarModel;
import com.ygqh.baby.po.YgPromotion;
import com.ygqh.baby.po.YgShoppingCar;
import com.ygqh.baby.po.YgStock;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.YgProductActionGiftService;
import com.ygqh.baby.service.YgPromotionService;
import com.ygqh.baby.service.YgStockService;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 〈〉
 *
 * @author guohao
 * @date 2018/12/28 13:36
 * @since 1.0.0
 */
@Component
public abstract class BaseShoppingCarHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private YgPromotionService ygPromotionService;
    @Autowired
    private DocumentConstant documentConstant;
    @Autowired
    private YgProductActionGiftService ygProductActionGiftService;
    @Autowired
    private YgStockService ygStockService;

    private final static String DISABLE_COUPON_KEY = "disablecoupon";


    public Message validateManZeng(List<YgShoppingCarModel> carList, SalesPlatform salesPlatform) {
        List<YgShoppingCarModel> manzengList = carList.stream().filter(carModel -> carModel.getSalesType().equals(PromotionType.ManZeng))
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(manzengList)) {
            return Message.success(null);
        }
        if (manzengList.size() > 1) {
            return Message.error(documentConstant.getMANZENG_AMOUNT_MORE(), null);
        }
        YgShoppingCarModel manzeng = manzengList.get(0);
        if (manzeng != null) {
            BigDecimal productPrice = carList.stream().map(carModel -> carModel.getRealSalesPrice().multiply(new BigDecimal(carModel.getQuantity())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            List<Long> productIds = carList.stream().map(YgShoppingCarModel::getProductId).collect(Collectors.toList());

            return validManzeng(productPrice, manzeng, productIds, salesPlatform);
        }
        return Message.success(null);
    }

    /**
     * 验证加价购
     *
     * @param carList 购物车
     * @return Message
     */
    public Message validateJiaJiaGou(List<YgShoppingCarModel> carList, SalesPlatform salesPlatform) {
        List<YgShoppingCarModel> jiajiagouList = carList.stream().filter(carModel -> carModel.getSalesType().equals(PromotionType.JiaJiaGou))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(jiajiagouList)) {
            return Message.success(null);
        }
        if (jiajiagouList.size() > 1) {
            return Message.error(documentConstant.getJIAJIAGOU_AMOUNT_MORE(), null);
        }
        YgShoppingCarModel jiajiagou = jiajiagouList.get(0);
        if (jiajiagou != null) {
            BigDecimal productPrice = carList.stream().map(carModel -> carModel.getRealSalesPrice().multiply(new BigDecimal(carModel.getQuantity())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            BigDecimal validPrice = productPrice.subtract(jiajiagou.getPromotionPrice());
            return validJiaJiaGou(validPrice, jiajiagou, salesPlatform);
        }
        return Message.success(null);
    }


    /**
     * 验证优惠券禁用设置 true--已设置并处于进行中， false--无效
     */
    @SuppressWarnings("rawtypes")
    public boolean validateDisableCouponFromRedis() {
        try {
            String couponInfo = redisDao.get(DISABLE_COUPON_KEY);
            Map map = JSON.parseObject(couponInfo, Map.class);
            if (MapUtils.isEmpty(map)) {
                return false;
            }
            Long currentTime = new Date().getTime();
            String startDate = map.get("startDate").toString();
            String endDate = map.get("endDate").toString();
            String format = "yyyy-MM-dd HH:mm:ss";
            Long startTime = DateConvertUtils.parse(startDate + " 00:00:00", format).getTime();
            Long endTime = DateConvertUtils.parse(endDate + " 23:59:59", format).getTime();
            if (startTime.compareTo(currentTime) > 0 || endTime.compareTo(currentTime) < 0) {
                return false;
            }
        } catch (Exception e) {
            logger.error("验证优惠券禁用设置异常，" + ExceptionUtil.getExceptionMsg(e));
            return false;
        }
        return true;
    }

    /**
     * 验证加价购
     *
     * @param ordinaryPrice 普通商品总额
     * @param jiajiagouCar
     * @return
     */
    public Message validateJiaJiaGou(BigDecimal ordinaryPrice, YgShoppingCar jiajiagouCar, SalesPlatform salesPlatform) {
        // 验证购物车中所选商品是否满足促销条件
        if (jiajiagouCar == null) {
            return Message.success("", "");
        } else {
            // 验证加价购
            List<YgPromotion> jiajiagouList = ygPromotionService.findPromotionBySkuId(jiajiagouCar.getSkuId(), PromotionType.JiaJiaGou, null, salesPlatform);
            // 该赠品是否存在促销加价购列表中
            if (jiajiagouList != null && jiajiagouList.size() > 0) {
                // 加价购与满赠只有一个梯度
                YgPromotion jiajiagou = jiajiagouList.get(0);

                // 购物车中加价金额与促销活动中加价金额一致 且 总金额大于等于促销限制金额
                if (jiajiagouCar.getPromotionPrice().equals(jiajiagou.getDiscountPrice()) && ordinaryPrice.compareTo(jiajiagou.getLimitPrice()) >= 0) {
                    return Message.success("");
                } else {
                    return Message.error(documentConstant.getORDER_PRICE_FOR_JIAJIAGOU_LESS(), "");
                }
            } else {
                return Message.error(documentConstant.getJIAJIAGOU_GUOQI(), "");
            }
        }
    }

    public Message validJiaJiaGou(BigDecimal validPrice, YgShoppingCarModel jiajiagou, SalesPlatform salesPlatform) {
        YgShoppingCar jiajiagouCar = new YgShoppingCar();
        jiajiagouCar.setId(jiajiagou.getId());
        jiajiagouCar.setSkuId(jiajiagou.getSkuId());
        jiajiagouCar.setPromotionPrice(jiajiagou.getPromotionPrice());
        return this.validateJiaJiaGou(validPrice, jiajiagouCar, salesPlatform);
    }

    /**
     * 验证满赠
     *
     * @param productPrice 商品总额 含加价购金额
     * @param manzengCar   满赠
     * @return Message
     */
    public Message validateManZeng(BigDecimal productPrice, YgShoppingCar manzengCar, List<Long> productIds, SalesPlatform salesPlatform) {
        if (manzengCar == null) {
            return Message.success("", "");
        } else {
            // 验证满赠
            List<YgPromotion> manzengList = ygPromotionService.findPromotionBySkuId(manzengCar.getSkuId(), PromotionType.ManZeng, productPrice, salesPlatform);
            // 该赠品是否存在满赠列表中
            if (manzengList != null && manzengList.size() > 0) {
                YgPromotion manzeng = manzengList.get(0);
                // 购物车中总金额 大于等于促销限制金额
                if (productPrice.compareTo(manzeng.getLimitPrice()) < 0) {
                    return Message.error(documentConstant.getORDER_PRICE_FOR_MANZENG_LESS(), "");
                }
            } else {
                Boolean gift = ygProductActionGiftService.checkSingleGift(productIds, manzengCar.getSkuId());
                if (!gift) {
                    return Message.error(documentConstant.getMANZENG_GUOQI(), "");
                }
            }
            return Message.success(null);
        }
    }

    public Message validManzeng(BigDecimal validPrice, YgShoppingCarModel manzeng, List<Long> productIds, SalesPlatform salesPlatform) {
        YgShoppingCar manzengCar = new YgShoppingCar();
        manzengCar.setId(manzeng.getId());
        manzengCar.setSkuId(manzeng.getSkuId());
        manzengCar.setPromotionPrice(manzeng.getPromotionPrice());
        return this.validateManZeng(validPrice, manzengCar, productIds, salesPlatform);
    }


    public Message checkStock(List<YgShoppingCarModel> carList) {
        Map<String, List<YgShoppingCarModel>> skuMap = carList.stream().collect(Collectors.groupingBy(YgShoppingCarModel::getSkuCode));

        List<String> skuCodeList = new ArrayList<>(skuMap.keySet());
        Map<String, List<YgStock>> stockMap = getStockMap(skuCodeList);

        for (Map.Entry<String, List<YgShoppingCarModel>> entry : skuMap.entrySet()) {
            String skuCode = entry.getKey();
            YgShoppingCarModel car = entry.getValue().get(0);
            String productName = car.getProductName();
            Long quantity = entry.getValue().stream().map(YgShoppingCarModel::getQuantity).reduce(0L, (a, b) -> (a + b));
            List<YgStock> ygStocks = stockMap.get(skuCode);
            if (CollectionUtils.isEmpty(ygStocks)) {
                return Message.error(productName + "库存不足", productName);
            }
            Long amount = ygStocks.get(0).getAmount();
            if (amount.compareTo(quantity) < 0) {
                return Message.error(productName + "库存不足", productName);
            }
        }
        return Message.success(null);
    }

    public Map<String, List<YgStock>> getStockMap(List<String> skuCodeList) {
        List<YgStock> stockList = ygStockService.findBySkuCodes(skuCodeList.toArray(new String[skuCodeList.size()]));
        return stockList.stream().collect(Collectors.groupingBy(YgStock::getSkuCode));
    }
}
